#include "stdafx.h"
#include "myExternal.h"

#define ext_hello 1
#define ext_getName 2
#define ext_getNameOver 3
myExternal::myExternal(myBaseIEObj *pIEOBj):
	m_pIEObj(pIEOBj)
{
	m_cmdMap[L"hello"] = ext_hello;
	m_cmdMap[L"getName"] = ext_getName;
	m_cmdMap[L"getNameOver"] = ext_getNameOver;
}
HRESULT myExternal::QueryInterface(const IID &riid, void** ppvObject)
{
	if (riid == IID_IUnknown) 
	{ 
		*ppvObject = (void*)(this); 
		return S_OK; 
	} 
	else if (riid == IID_IDispatch)
	{
		*ppvObject = (IDispatch*)(this); 
		return S_OK; 
	}
	return E_NOINTERFACE;
}

HRESULT myExternal::GetTypeInfoCount(UINT* /*pctinfo*/) { return E_NOTIMPL; }
HRESULT myExternal::GetTypeInfo(UINT /*iTInfo*/, LCID /*lcid*/, ITypeInfo** /*ppTInfo*/) { return E_NOTIMPL; }

HRESULT myExternal::GetIDsOfNames(REFIID /*riid*/, LPOLESTR* rgszNames, UINT cNames, LCID /*lcid*/, DISPID* rgDispId)
{
	HRESULT hr = NOERROR;
	for (UINT i = 0; i < cNames; i++)
	{
		std::wstring wstrCommand = rgszNames[i];
		CommandIDMap::iterator it = m_cmdMap.find(wstrCommand);
		if (it != m_cmdMap.end())
		{
			rgDispId[i] = it->second;
		}
		else
		{
			hr = ResultFromScode(DISP_E_UNKNOWNNAME);
			rgDispId[i] = DISPID_UNKNOWN;
		}
	}

	return hr;
}

HRESULT myExternal::Invoke(DISPID dispIdMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pVarResult, EXCEPINFO* pExcepInfo, UINT* puArgErr)
{
	switch(dispIdMember){
		case ext_hello:
			MessageBox(NULL, L"hello world!", L"yes", MB_OK);
			break;
		case ext_getName:
			return onGetName(pDispParams, pVarResult);
		case ext_getNameOver:
			m_pIEObj->OnGetNameOver();
			break;
		default:
			break;
	}
	return S_OK;
}

HRESULT myExternal::onGetName(DISPPARAMS* pDispParams, VARIANT* )
{
	if (1 == pDispParams->cArgs){
		unsigned int uArgErr;
		CComVariant var;
		::DispGetParam(pDispParams, 0, VT_BSTR, &var, &uArgErr) ;
		std::wstring wstrName = var.bstrVal;
		m_pIEObj->OnGetName(wstrName);
	}
	return S_OK;
}